<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import { ElMessage, ElTree } from 'element-plus'
import wsjzglService from '@/api/wsjzgl'
import AddDialog from './dialogs/add-dialog.vue'
import MlmbDialog from './dialogs/mlmb-dialog.vue'
import AddmlDialog from './dialogs/add-ml-dialog.vue'
import UpdatemlDialog from './dialogs/update-ml-dialog.vue'
import zzmlDialog from './dialogs/zzml-dialog.vue'
import TreeUtilDTO from '@/utils/tree'
import { useMainStore } from '@/store/main'
import { useRoute } from 'vue-router'
const route = useRoute()

const emit = defineEmits(['nodeClick', 'updatePage'])
const store = useMainStore()
// 入参

// 生命周期
// onMounted(() => {
//   // 查询树
//   queryTree()
// })

const init = () => {
  queryTree()
  treeNodeData.value = {}
}

const filterForm = ref({
  gjzValue: '',
  mlSelect: '0',
})

const defaultProps = {
  children: 'children',
  label: 'mc',
}
const treeData = ref<any>([])
// const selectTreeData = ref<any>([])
const firtsNode = ref<any>()
/*
 * 查询树
 */
const queryTree = () => {
  const params = {
    ajbh: route.query.ajbh as unknown as string,
    mlmc: '',
    mlxslx: mlxslx.value,
  }
  wsjzglService
    .queryAjmls(params)
    .then((res) => {
      let obj = route.query
      const dbmNode = res.data?.find((item: any) => item.mc === '待编目材料')
      const zjNode = res.data?.find((item: any) => item.mc === '正卷')
      const fjNode = res.data?.find((item: any) => item.mc === '副卷')
      store.saveJzsmDbmNode(dbmNode)
      store.saveZjNode(zjNode)
      store.saveFjNode(fjNode)
      res.data?.forEach((item: any) => {
        if (!item.fbh) {
          item['fbh'] = obj.ajbh
        }
      })
      //处理数据
      res.data.push({
        ajbhaj: obj.ajbh,
        bh: obj.ajbh,
        mc: obj.ajmc,
        wjsl: 0,
      })

      treeData.value = TreeUtilDTO.getTreeData(res.data, 'bh', 'fbh')
      treeData.value?.forEach((data: any) => {
        if (data.children && data.children.length > 0) {
          data.children = data.children.filter((el: any) => {
            return el.mc !== '待编目材料'
          })
          data.children.forEach((data1: any) => {
            data.wjsl += data1.wjsl
            if (data1.children) {
              data1.children = data1.children.sort((a: any, b: any) => a.mlsxh - b.mlsxh)
            }
          })
        }
      })

      if (treeData.value.length) {
        firtsNode.value = null
        // 递归选择第一个
        getFirstNode(treeData.value)
        if (firtsNode.value) {
          handleCheckNode(firtsNode.value)
        }
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

const getFirstNode = (arr: any[]) => {
  if (firtsNode.value) return
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].children && arr[i].children.length > 0) {
      getFirstNode(arr[i].children)
    } else {
      firtsNode.value = arr[i]
    }
    return
  }
}

const handleCheckNode = (node: any) => {
  nextTick(() => {
    if (treeNodeData.value?.bh === node.bh) {
      return
    }
    const ml = TreeUtilDTO.findNode(treeData.value, node.ajbh, 'bh')
    treeNodeData.value = node
    emit('nodeClick', treeNodeData.value, ml?.children)
    treeRef.value!.setCurrentKey(node.bh)
  })
}

/*
 * 树节点点击（抛出方法到主界面）
 */
const treeNodeData = ref<any>({})
const treeNodeClick = (data: any) => {
  if (treeNodeData.value?.bh === data.bh) {
    return
  }
  treeNodeData.value = data

  if (data.ajbh !== store.$state.nodeTreeData?.ajbh) {
    const ml = TreeUtilDTO.findNode(treeData.value, data.ajbh, 'bh')
    emit('nodeClick', treeNodeData.value, ml?.children)
  } else {
    emit('nodeClick', treeNodeData.value)
    const params = {
      ajbh: data.ajbh,
      mlbh: data.bh,
    }
    wsjzglService
      .queryWjList(params)
      .then((res) => {
        nextTick(() => {
          if (res.data.length) {
            emit('updatePage', res.data[0].wjbh)
          }
        })
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
  }
}

// 抛出去刷新再请求一次方法
const againTreeData = () => {
  const params = {
    ajbh: route.query.ajbh as unknown as string,
    mlmc: '',
    mlxslx: mlxslx.value,
  }
  wsjzglService
    .queryAjmls(params)
    .then((res) => {
      let obj = route.query
      const dbmNode = res.data?.find((item: any) => item.mc === '待编目材料')
      const zjNode = res.data?.find((item: any) => item.mc === '正卷')
      const fjNode = res.data?.find((item: any) => item.mc === '副卷')
      store.saveJzsmDbmNode(dbmNode)
      store.saveZjNode(zjNode)
      store.saveFjNode(fjNode)
      res.data?.forEach((item: any) => {
        if (!item.fbh) {
          item['fbh'] = obj.ajbh
        }
      })
      //处理数据
      res.data.push({
        ajbhaj: obj.ajbh,
        bh: obj.ajbh,
        mc: obj.ajmc,
        wjsl: 0,
      })
      treeData.value = TreeUtilDTO.getTreeData(res.data, 'bh', 'fbh')
      treeData.value?.forEach((data: any) => {
        if (data.children && data.children.length > 0) {
          data.children = data.children.filter((el: any) => {
            return el.mc !== '待编目材料'
          })
          data.children.forEach((data1: any) => {
            data.wjsl += data1.wjsl
            if (data1.children) {
              data1.children = data1.children.sort((a: any, b: any) => a.mlsxh - b.mlsxh)
            }
          })
        }
      })
      nextTick(() => {
        treeRef.value!.setCurrentKey(store.$state.nodeTreeData?.bh)
      })
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/*
 * 拖拽节点
 */

const handleDrop = (draggingNode: any, dropNode: any) => {
  const temp = TreeUtilDTO.findNode(treeData.value, dropNode.data.fbh, 'bh')
  const params = {
    list: temp.children.map((el: any, i: number) => ({
      ajbh: el.ajbh,
      fmlbh: el.fmlbh,
      mlbh: el.bh,
      mlsxh: i + 1,
    })),
  }
  wsjzglService.updateMlgs(params, route.query.ajbh as string).catch((err) => {
    !err.isError && ElMessage({ type: 'warning', message: err.message })
  })
}

// 判断节点是否能被拖动
const allowDrag = (node: any) => {
  let flag = true
  if (node.data.cj === '2') {
    flag = true
  } else {
    flag = false
  }
  return flag
}

//目标节点能否成为拖动目标位置
const allowDrop = (draggingNode: any, dropNode: any, type: any) => {
  if (draggingNode.data.cj === dropNode.data.cj) {
    return type === 'prev' || type === 'next'
  } else if (draggingNode.data.cj === '2' && dropNode.data.cj === '1') {
    return type === 'inner'
  } else {
    return false
  }
}

/* 获取ref */
const addDialog = ref()
const mlmbDialog = ref()
const addmlDialog = ref()
const updatemlDialog = ref()

/*
 * 打开纸质目录弹框
 */
const zzmlDialogRef = ref()

const treeRef = ref<InstanceType<typeof ElTree>>()

// 文字过滤
const filterTree = () => {
  treeRef.value?.filter(filterForm.value.gjzValue)
}

const mlxslx = ref('0')

/**
 * 树节点过滤
 */
const filterNode = (value: any, data: any) => {
  let flag = true
  if (value) {
    if (typeof value === 'string') {
      // 文字过滤
      flag = data[defaultProps.label].indexOf(value) !== -1
    }
  }
  return flag
}

const options = [
  {
    value: '0',
    label: '所有目录',
  },
  {
    value: '1',
    label: '纸质目录',
  },
]

// 下拉过滤
const mlSelectChange = (val: string) => {
  mlxslx.value = val
  queryTree()
}

defineExpose({ init, againTreeData })
</script>
<template>
  <div class="container">
    <div class="center">
      <el-row :gutter="10" style="align-items: center">
        <el-col :span="16">
          <el-input
            v-model="filterForm.gjzValue"
            autosize=""
            placeholder="请输入查询关键字"
            @change="filterTree"
          >
            <template #suffix>
              <el-icon @click="filterTree" class="el-input__icon"><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-select v-model="filterForm.mlSelect" placeholder="请选择" @change="mlSelectChange">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            /> </el-select
        ></el-col>
      </el-row>
    </div>
    <div class="bottom">
      <el-tree
        ref="treeRef"
        style="max-width: 600px"
        :data="treeData"
        node-key="bh"
        highlight-current
        default-expand-all
        :expand-on-click-node="false"
        :props="defaultProps"
        @node-click="treeNodeClick"
        :filter-node-method="filterNode"
        @node-drop="handleDrop"
        :allow-drag="allowDrag"
        :allow-drop="allowDrop"
      >
        <template #default="{ data }">
          <div class="custom-tree-node">
            <!-- <el-icon v-if="data.fbh"> <FolderOpened /></el-icon> -->
            <img v-if="!data.fbh" src="/src/assets/images/file-icon.png" alt="" />
            <img
              v-if="data.mc === '正卷' || data.mc === '副卷'"
              src="/src/assets/images/dbm.png"
              alt=""
            />
            <img v-if="data.mc === '待编目材料'" src="/src/assets/images/juan.png" alt="" />
            <img
              v-if="data.cj === '2' && data.sfdzajml === 'Y' && (data.sfyy === 'N' || !data.sfyy)"
              style="margin-right: 5px"
              src="/src/assets/images/xswjwyz.png"
              alt=""
            />
            <img
              v-if="data.cj === '2' && data.sfdzajml === 'Y' && data.sfyy === 'Y'"
              style="margin-right: 5px"
              src="/src/assets/images/xsxwjyyz.png"
              alt=""
            />
            <img
              v-if="data.cj === '2' && (data.sfzzajml === 'Y' || !data.sfzzajml)"
              src="/src/assets/images/xxwj.png"
              alt=""
            />
            <span :class="data.cj === '2' ? 'over-title' : ''" :title="data.mc"
              >&nbsp;{{ data.mc }}&nbsp;</span
            >
            <span>({{ data.wjsl }})</span>
          </div>
        </template>
      </el-tree>
    </div>
    <AddDialog ref="addDialog" @refresh="queryTree" />
    <MlmbDialog ref="mlmbDialog" @refresh="queryTree" />
    <AddmlDialog ref="addmlDialog" @refresh="queryTree" />
    <UpdatemlDialog ref="updatemlDialog" />
    <!-- 纸质目录 -->
    <zzmlDialog ref="zzmlDialogRef"></zzmlDialog>
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  // padding: 5px;
  .top {
    margin-bottom: 10px;
  }
  .center {
    padding-bottom: 10px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.15);
  }
  .bottom {
    height: calc(100% - 43px);
    overflow-y: auto;
  }
}
.add-aj {
  width: 100%;
}
.el-input__icon {
  cursor: pointer;
}

.custom-tree-node {
  width: calc(100% - 40px);
  display: flex;
  align-items: center;
  .over-title {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}

:deep(.el-tabs .el-tabs__content) {
  height: calc(100% - 40px);
  /* overflow: auto; */
  padding: 0;
}
</style>
